package com.banzhi.shop.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.banzhi.shop.MyApp;
import com.banzhi.shop.R;
import com.banzhi.shop.base.BaseActivity;
import com.banzhi.shop.entity.ShopInformation.Shop_Data;
import com.banzhi.shop.model.CallBack.InputPicturesCallBack;
import com.banzhi.shop.model.CallBack.ShopInformationCallBack;
import com.banzhi.shop.model.IInputPictureModel;
import com.banzhi.shop.model.IShopInformationModel;
import com.banzhi.shop.model.Impl.InputPictureImpl;
import com.banzhi.shop.model.Impl.ShopInformationImpl;
import com.banzhi.shop.utils.ASUtils;
import com.banzhi.shop.utils.BitmapUtils;
import com.banzhi.shop.utils.LoadingDialogUtils;
import com.banzhi.shop.utils.NoTokenUtils;
import com.banzhi.shop.utils.PermissionsChecker;
import com.banzhi.shop.utils.TemplatePopupwindowUtils;
import com.banzhi.shop.utils.ToastUtils;
import com.banzhi.shop.utils.Translucent;
import com.banzhi.shop.view.CircleImageView;
import com.squareup.picasso.Picasso;

import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;

/**
 * 店铺信息
 */
public class ShopInformationActivity extends BaseActivity implements View.OnClickListener, ShopInformationCallBack, InputPicturesCallBack {
    private ImageView ivback;
    /**
     * logo照片
     */
    private CircleImageView civ_logo;
    /**
     * 店铺名字
     */
    private TextView tvshopname;
    /**
     * 保存
     */
    private Button btnsave;

    private IShopInformationModel model;
    private Shop_Data data;

    private ImageView ivbackground;
    private TextView tvjieshao;
    /**
     * 店铺预览
     */
    private TextView tvyulan;
    /**
     * 店铺logo布局
     */
    private LinearLayout lllogo;
    /**
     * 店铺名称
     */
    private LinearLayout llshopname;
    /**
     * 店铺介绍
     */
    private LinearLayout llshopintroduce;
    /**
     * 店铺背景
     */
    private LinearLayout llshopbackground;
    private IInputPictureModel picmodel;

    /**
     * 裁剪后的照片文件
     */
    private File Imagefile;
    /**
     * 上传头像后返回的头像的网络地址
     */
    private String imageURL;
    /**
     * 上传背景图片后返回的头像的网络地址
     */
    private String backgroundURL;
    private Bitmap bitmap;
    private File dir;
    private PermissionsChecker mPermissionsChecker; // 权限检测器
    static final String[] PERMISSIONS = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA};
    private DisplayMetrics dm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_information);
        Translucent.setTranslucent(this);
        mPermissionsChecker = new PermissionsChecker(this);
        setinits();
        setListeners();
        picmodel = new InputPictureImpl();
        model = new ShopInformationImpl();

        if (!"".equals(MyApp.loginMessage.getString("shopname", ""))) {
            showViews();
        } else {
            LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
            model.getData(this);
        }
    }


    private void setinits() {
        dm = getResources().getDisplayMetrics();
        ivback = (ImageView) findViewById(R.id.iv_back);
        ivbackground = (ImageView) findViewById(R.id.iv_background);
        civ_logo = (CircleImageView) findViewById(R.id.civ_logo);
        tvshopname = (TextView) findViewById(R.id.tv_shopname);
        tvjieshao = (TextView) findViewById(R.id.tv_jieshao);
        lllogo = (LinearLayout) findViewById(R.id.ll_logo);
        llshopname = (LinearLayout) findViewById(R.id.ll_shopname);
        llshopintroduce = (LinearLayout) findViewById(R.id.ll_shop_introduce);
        llshopbackground = (LinearLayout) findViewById(R.id.ll_shop_background);
        btnsave = (Button) findViewById(R.id.btn_save);
    }

    private void setListeners() {
        ivback.setOnClickListener(this);
        lllogo.setOnClickListener(this);
        llshopname.setOnClickListener(this);
        llshopintroduce.setOnClickListener(this);
        llshopbackground.setOnClickListener(this);
        btnsave.setOnClickListener(this);
    }

    private String type;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.ll_logo:
                type = "logo";
                showImagePopwindow();
                break;
            case R.id.ll_shopname:
                showShopnamePopwindow();
                break;
            case R.id.ll_shop_introduce:
                Intent intent = new Intent(this, ShopIntroduceActivity.class);
                intent.putExtra("data", tvjieshao.getText().toString().trim());
                startActivityForResult(intent, 100);
                break;
            case R.id.ll_shop_background:
                type = "background";
                showImagePopwindow();
                break;
            case R.id.btn_save:
                if (!ASUtils.isCanUse(tvshopname.getText().toString().trim())) {
                    ToastUtils.makeToastShort("请先输入店铺名称");
                } else {
                    LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
                    if (ASUtils.isCanUse(imageURL)) {
                        if (ASUtils.isCanUse(backgroundURL)) {
                            LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
                            model.ChangeShop(imageURL, tvshopname.getText().toString().trim(), backgroundURL, tvjieshao.getText().toString().trim(), this);
                        } else {
                            LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
                            model.ChangeShop(imageURL, tvshopname.getText().toString().trim(), MyApp.loginMessage.getString("shopimg", ""), tvjieshao.getText().toString().trim(), this);
                        }
                    } else {
                        if (ASUtils.isCanUse(backgroundURL)) {
                            LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
                            model.ChangeShop(MyApp.loginMessage.getString("shoplogo", ""), tvshopname.getText().toString().trim(), backgroundURL, tvjieshao.getText().toString().trim(), this);
                        } else {
                            LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
                            model.ChangeShop(MyApp.loginMessage.getString("shoplogo", ""), tvshopname.getText().toString().trim(), MyApp.loginMessage.getString("shopimg", ""), tvjieshao.getText().toString().trim(), this);
                        }
                    }
                }
                break;
        }
    }


    private void showShopnamePopwindow() {
        //设置contentView
        View contentView = LayoutInflater.from(ShopInformationActivity.this).inflate(R.layout.popupwindow_input_shopname, null);
        final PopupWindow popWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        popWindow.setContentView(contentView);
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(true);// 设置允许在外点击消失

        final EditText etname = (EditText) contentView.findViewById(R.id.et_name);
        TextView tvsave = (TextView) contentView.findViewById(R.id.tv_save);
        TextView tvcancle = (TextView) contentView.findViewById(R.id.tv_cancle);
        RelativeLayout rlbackground = (RelativeLayout) contentView.findViewById(R.id.rl_background);
        LinearLayout ll = (LinearLayout) contentView.findViewById(R.id.ll);
        rlbackground.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
        ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        if (ASUtils.isCanUse(tvshopname.getText().toString().trim())) {
            etname.setText(tvshopname.getText().toString().trim());
        }
        tvsave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!ASUtils.isCanUse(etname.getText().toString().trim())) {
                    ToastUtils.makeToastShort("请先输入店铺名称");
                } else {
                    tvshopname.setText(etname.getText().toString().trim());
                    popWindow.dismiss();
                }
            }
        });
        tvcancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
        ColorDrawable dw = new ColorDrawable(0x70000000);
        popWindow.setBackgroundDrawable(dw);
        popWindow.showAtLocation(contentView, Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    private void showViews() {
        tvshopname.setText(MyApp.loginMessage.getString("shopname", ""));
        if (ASUtils.isCanUse(MyApp.loginMessage.getString("shoplogo", ""))) {
            Picasso.with(this).load(MyApp.loginMessage.getString("shoplogo", "")).placeholder(R.mipmap.zhanweitu2).into(civ_logo);
        }
        if (ASUtils.isCanUse(MyApp.loginMessage.getString("shopimg", ""))) {
            Picasso.with(this).load(MyApp.loginMessage.getString("shopimg", "")).placeholder(R.mipmap.zhanweitu2).into(ivbackground);
        }
        tvjieshao.setText(MyApp.loginMessage.getString("shopDescription", ""));

    }

    /**
     * @param object 获取店铺信息成功
     */
    @Override
    public void ongetDataSuccess(Object object) {
        data = (Shop_Data) object;
        SharedPreferences.Editor editor = MyApp.loginMessage.edit();
        editor.putString("shopname", data.getShopName());
        editor.putString("shoplogo", data.getShopLogo());
        editor.putString("shopimg",  data.getImg());
        editor.putString("shopDescription", data.getDescription());
        editor.putString("recommendName", data.getRecommendName());
        editor.apply();
        showViews();
    }


    /**
     * @param object 获取店铺信息失败
     */
    @Override
    public void ongetDataError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    /**
     * @param object 修改店铺成功
     */
    @Override
    public void changeShopSuccess(Object object) {
        ToastUtils.makeToastShort("保存成功");
        model.getData(this);
    }

    /**
     * @param object 修改店铺失败
     */
    @Override
    public void changeShopError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    /**
     * @param object 上传图片成功
     */
    @Override
    public void inputSuccess(Object object, String type) {
        JSONObject jsonObject = (JSONObject) object;
        if ("logo".equals(type)) {
            imageURL = jsonObject.optString("res");
            if (ASUtils.isCanUse(imageURL)) {
                Picasso.with(this).load(imageURL).placeholder(R.mipmap.zhanweitu2).into(civ_logo);
            } else {
                civ_logo.setImageBitmap(bitmap); // 将裁剪后的照片显示出来
            }
        } else if ("background".equals(type)) {
            backgroundURL = jsonObject.optString("res");
            if (ASUtils.isCanUse(backgroundURL)) {
                Picasso.with(this).load(backgroundURL).placeholder(R.mipmap.zhanweitu2).into(ivbackground);
            } else {
                ivbackground.setImageBitmap(bitmap); // 将裁剪后的照片显示出来
            }
        }

    }

    /**
     * @param object 上传图片失败
     */
    @Override
    public void inputError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    private static final int CODE_GALLERY_REQUEST = 0x1;
    private static final int CODE_CAMERA_REQUEST = 0x2;
    private static final int CROP_PICTURE_REQUEST = 0x3;

    private static final String TEMP_FILE_NAME = "temp_icon.jpg";

    /**
     * Save the path of photo cropping is completed
     */
    private Uri icon_path;
    private Uri camera_path;

    /**
     * 选择头像
     */
    private void showImagePopwindow() {
        View contentView = LayoutInflater.from(this).inflate(R.layout.popwindow_image, null);
        final PopupWindow popWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        popWindow.setContentView(contentView);

        Button btnCamera = (Button) contentView.findViewById(R.id.btn_camera_pop_camera);
        Button btnAlbum = (Button) contentView.findViewById(R.id.btn_camera_pop_album);
        Button btnCancel = (Button) contentView.findViewById(R.id.btn_camera_pop_cancel);
        popWindow.setAnimationStyle(R.style.AnimBottom);
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(false);// 设置允许在外点击消失
        RelativeLayout rlbackground = (RelativeLayout) contentView.findViewById(R.id.rl_background);
        LinearLayout ll = (LinearLayout) contentView.findViewById(R.id.ll);
        rlbackground.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
        ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        View.OnClickListener listener = new View.OnClickListener() {
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.btn_camera_pop_camera:
                        //检查权限(6.0以上做权限判断)
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            if (mPermissionsChecker.lacksPermissions(PERMISSIONS)) {
                                requestPermissions(PERMISSIONS, 1000);
                            } else {
                                openCamera();
                            }
                        } else {
                            openCamera();
                        }
                        break;
                    case R.id.btn_camera_pop_album:
                        //检查权限(6.0以上做权限判断)
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            if (mPermissionsChecker.lacksPermissions(PERMISSIONS)) {
                                requestPermissions(new String[]{PERMISSIONS[1]}, 1100);
                            } else {
                                selectFromAlbum();
                            }
                        } else {
                            selectFromAlbum();
                        }
                        break;
                    case R.id.btn_camera_pop_cancel:

                        break;

                }
                popWindow.dismiss();
            }
        };

        btnCamera.setOnClickListener(listener);
        btnAlbum.setOnClickListener(listener);
        btnCancel.setOnClickListener(listener);

        ColorDrawable dw = new ColorDrawable(0x70000000);
        popWindow.setBackgroundDrawable(dw);
        popWindow.showAtLocation(contentView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    /**
     * 打开系统相机
     */
    private void openCamera() {
        dir = getExternalFilesDir("user_icon");
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            icon_path = FileProvider.getUriForFile(getApplicationContext(),
                    getPackageName() + ".fileprovider", new File(dir, TEMP_FILE_NAME));
            camera_path = FileProvider.getUriForFile(getApplicationContext(),
                    getPackageName() + ".fileprovider", new File(dir, "camera_pic.jpg"));
        } else {
            icon_path = Uri.fromFile(new File(dir, TEMP_FILE_NAME));
            camera_path = Uri.fromFile(new File(dir, "camera_pic.jpg"));
        }
        Intent intentFromCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT, camera_path);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            intentFromCapture.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        startActivityForResult(intentFromCapture, CODE_CAMERA_REQUEST);

    }

    /**
     * 从相册选择
     */
    private void selectFromAlbum() {
        dir = getExternalFilesDir("user_icon");
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            icon_path = FileProvider.getUriForFile(ShopInformationActivity.this,
                    getPackageName() + ".fileprovider", new File(dir, TEMP_FILE_NAME));
            camera_path = FileProvider.getUriForFile(ShopInformationActivity.this,
                    getPackageName() + ".fileprovider", new File(dir, "camera_pic.jpg"));
        } else {
            icon_path = Uri.fromFile(new File(dir, TEMP_FILE_NAME));
            camera_path = Uri.fromFile(new File(dir, "camera_pic.jpg"));
        }
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//        Intent intentFromGallery = new Intent();
//        intentFromGallery.setType("image/*");
//        intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, CODE_GALLERY_REQUEST);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_CANCELED) {
            return;
        }
        switch (requestCode) {
            case CODE_GALLERY_REQUEST:
                if ("background".equals(type)) {
                    cropImage(data.getData(), 40, 19, 800, 380, CROP_PICTURE_REQUEST);
                } else {
                    cropImage(data.getData(), 1, 1, 450, 450, CROP_PICTURE_REQUEST);
                }
                break;
            case CODE_CAMERA_REQUEST:
                if ("background".equals(type)) {
                    cropImage(camera_path, 40, 19, 800, 380, CROP_PICTURE_REQUEST);
                } else {
                    cropImage(camera_path, 1, 1, 450, 450, CROP_PICTURE_REQUEST);
                }
                break;
            case CROP_PICTURE_REQUEST:
                bitmap = decodeUriAsBitmap(icon_path);
                Imagefile = BitmapUtils.saveBitmapFile(bitmap, "camera");
                picmodel.getData(Imagefile, type, this);
                bitmap = null;
                break;
            case 100:
                if (resultCode == 200) {
                    tvjieshao.setText(data.getStringExtra("data"));
                }
                break;

        }
    }

    /**
     * According to the incoming a length-width ratio began to cut out pictures
     *
     * @param uri Image source
     */
    private void cropImage(Uri uri, int aspectX, int aspectY, int outputX, int outputY, int requestCode) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // Set the cutting
        intent.putExtra("crop", "true");
        // aspectX , aspectY :In proportion to the width of high
        intent.putExtra("aspectX", aspectX);
        intent.putExtra("aspectY", aspectY);
        // outputX , outputY : High cutting image width
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
        intent.putExtra("scale", true);
        intent.putExtra("scaleUpIfNeeded", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, icon_path);
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            addurlPram(this, intent, camera_path, icon_path);
        }
        startActivityForResult(intent, requestCode);
    }

    private void addurlPram(Activity activity, Intent intent, Uri... uris) {
        List<ResolveInfo> resInfoList = activity.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        for (ResolveInfo resolveInfo : resInfoList) {
            String packageName = resolveInfo.activityInfo.packageName;
            for (Uri uri : uris) {
                activity.grantUriPermission(packageName, uri,
                        Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
            }
        }
    }

    private Bitmap decodeUriAsBitmap(Uri uri) {
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
        return bitmap;
    }

    //Android6.0申请权限的回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            // requestCode即所声明的权限获取码，在checkSelfPermission时传入
            case 1000:
                if (mPermissionsChecker.lacksPermissions(PERMISSIONS)) {
                    TemplatePopupwindowUtils.showPermissionsPopupWindow(ShopInformationActivity.this, "当前功能缺失必要权限", "请手动开启");
                } else {
                    openCamera();
                }
                break;
            case 1100:
                if (mPermissionsChecker.lacksPermissions(PERMISSIONS[1])) {
                    TemplatePopupwindowUtils.showPermissionsPopupWindow(ShopInformationActivity.this, "当前功能缺失必要权限", "请手动开启");
                } else {
                    selectFromAlbum();
                }
                break;
        }
    }
}
